package com.wisdom.smartbook.utils;

import android.app.Service;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.DisplayMetrics;

import com.wisdom.smartbook.app.MyApp;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;


public class DeviceUtil {

    public static int deviceWidth() {
//        LogUtil.e("deviceWidth");
        DisplayMetrics displayMetrics = MyApp.getAppContext().getResources().getDisplayMetrics();
//        LogUtil.e("widthP="+displayMetrics.widthPixels);
//        LogUtil.e("displayMetrics.heightPixels="+displayMetrics.heightPixels);
//        if(displayMetrics.widthPixels < displayMetrics.heightPixels){
        return displayMetrics.widthPixels;
//        }else {
//            return displayMetrics.heightPixels;
//        }
    }

    public static int deviceHeight() {
//        LogUtil.e("deviceHeight");
        DisplayMetrics displayMetrics = MyApp.getAppContext().getResources().getDisplayMetrics();
//        LogUtil.e("heightP="+displayMetrics.heightPixels);
//        if(displayMetrics.widthPixels < displayMetrics.heightPixels){
        return displayMetrics.heightPixels;
//        }else {
//            return displayMetrics.widthPixels;
//        }
    }

    /**
     * 获取WiFi mac地址
     *
     * @param context
     * @return
     */
    public static String getWifiMac(Context context) {
        String mac = null;
        if (context != null) {
            WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = wifi.getConnectionInfo();
            mac = info.getMacAddress();
        }
        return mac;
    }

    /**
     * 获取Android ID，这个在重置系统后，会变
     *
     * @param context
     * @return
     */
    public static String getAndroidId(Context context) {
        String id = null;
        if (context != null) {
            id = Settings.System.getString(context.getContentResolver(),
                    Settings.Secure.ANDROID_ID);
        }
        return id;
    }

    /**
     * eth0 MAC地址获取，适用api9 - api24
     */
    public static String getEth0Mac() {

        String Mac = "";
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("eth0")) continue;

                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return "Didn\'t get eth0 MAC address";
                }
                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }
                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                    Mac = res1.toString();
                }
                return Mac;
            }
        } catch (Exception ex) {
        }
        return "Didn\'t get eth0 MAC address";
    }

    /**
     * wlan0 MAC地址获取，适用api9 - api24
     */
    public static String getWlan0Mac() {

        String Mac = "";
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0")) continue;

                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return "Didn\'t get Wlan0 MAC address";
                }
                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }

                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                    Mac = res1.toString();
                }
                return Mac;
            }
        } catch (Exception ex) {
        }
        return "Didn\'t get Wlan0 address";
    }

    /**
     * 取得 Mac-Address
     * 1. 先取得 eth0 Mac-Address
     * 2. 再取得 wlan0 Mac-Address
     *
     * @return
     */
    public static String getDeviceMacAddress() {
        String mac = !getEth0Mac().equals("Didn\'t get eth0 MAC address") ? getEth0Mac() : getWlan0Mac();
        return mac;
    }


    public static void printDeviceInfo() {
        DisplayMetrics dm = MyApp.getAppContext().getResources().getDisplayMetrics();
//手机宽度dp值 = 手机实际宽度像素px / 手机屏幕密度比
        float widthDP = dm.widthPixels / dm.density;
// dm.heightPixels 表示手机实际高度像素px
        float heightDP = dm.heightPixels / dm.density;

        KLog.e("手机屏幕宽度*高度/px是: " + dm.widthPixels + "*" + dm.heightPixels);
        KLog.e("手机屏幕宽度/dp是: " + widthDP);
        KLog.e("手机屏幕高度/dp是: " + heightDP);
        KLog.e("手机实际宽度像素dp是: " + dm.widthPixels);
        KLog.e("手机屏幕密度比是: " + dm.density);
        KLog.e("手机屏幕显示dpi是: " + dm.densityDpi);
    }


    /**
     * 2点连线，与水平线的夹角
     *
     * @param x1
     * @param y1
     * @param x2
     * @param y2
     * @return
     */
    public static int calAngle(double x1, double y1, double x2, double y2) {
        double x = Math.abs(x1 - x2);
        double y = Math.abs(y1 - y2);
        double z = Math.sqrt(x * x + y * y);
        int angle = Math.round((float) (Math.asin(y / z) / Math.PI * 180));
        return angle;
    }

    public static String getMacData() {
        //获取有线网络的mac地址
        String eth0Mac = getMac("eth0");
        //获取wifi下的mac地址
        String wlan0Mac = getMac("wlan0");
        KLog.d("wlan0Mac:" + wlan0Mac);
        if (!TextUtils.isEmpty(eth0Mac)) {
            return eth0Mac.replaceAll(":", "");
        } else {
            if (!TextUtils.isEmpty(wlan0Mac)) {
                return wlan0Mac.replaceAll(":", "");
            }
        }
        return "";
    }

    public static String getMac(String name) {
        try {
            NetworkInterface ni = NetworkInterface.getByName(name);
            if (ni != null) {
                byte[] bytesMac = ni.getHardwareAddress();
                if (bytesMac != null) {
                    StringBuilder sb = new StringBuilder();
                    byte[] mac = bytesMac;
                    int length = bytesMac.length;
                    for (int i = 0; i < length; ++i) {
                        byte b = mac[i];
                        sb.append(String.format("%02x:", b));
                    }
                    if (sb.length() > 0) {
                        sb.deleteCharAt(sb.length() - 1);
                    }
                    return sb.toString();
                }
            }
        } catch (Exception var8) {
            var8.printStackTrace();
        }
        return "";
    }

    /**
     * 根据余弦定理计算线段1到线段2的夹角，线段1：起始点到原点，线段2：原点到结束点）
     *
     * @return
     */
    public static double calThreeAngle(double oneX, double oneY, double twoX, double twoY, double threeX, double threeY) {
        double cosfi = 0;
        double fi = 0;
        double norm = 0;
        double dsx = oneX - twoX;
        double dsy = oneY - twoY;
        double dex = threeX - twoX;
        double dey = threeY - twoY;
        cosfi = dsx * dex + dsy * dey;
//        System.out.println("cosfi="+cosfi);
        norm = (dsx * dsx + dsy * dsy) * (dex * dex + dey * dey);
        cosfi /= Math.sqrt(norm);
//        System.out.println("norm="+norm);
//        System.out.println("cosfi="+cosfi);
        if (cosfi >= 1.0) return 0;
        if (cosfi <= -1.0) return Math.PI;
        fi = Math.acos(cosfi);
//        System.out.println("fi="+fi);
//        System.out.println("Math.toDegrees(fi)="+Math.toDegrees(5.4));

        if (180 * fi / Math.PI < 180) {
            return 180 * fi / Math.PI;
        } else {
            return 360 - 180 * fi / Math.PI;
        }
    }

    /**
     * 2个点的距离
     *
     * @param x1,y1
     * @param x2,y2
     * @return 距离
     */
    public static Double getDisByTwoPoint(double x1, double y1, double x2, double y2) {
        return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
    }

    /**
     * 2点连线，与水平线的夹角
     *
     * @return
     */
    public static double calAngle180(double shoulderX, double shoulderY, double hipX, double hipY, double knee_y) {
        if (shoulderY < knee_y) {
            return  calThreeAngle(shoulderX,shoulderY,hipX,hipY,hipX,0);
        }else {
            return  calThreeAngle(shoulderX,shoulderY,hipX,hipY,hipX,3000);
        }
    }



    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static double calcRotationAngleInDegrees(double oneX, double oneY, double twoX, double twoY) {
        double theta = Math.atan2(oneY - twoY, oneX - twoX);
        theta += Math.PI/2.0;
        double angle = Math.toDegrees(theta);
        if (angle < 0) {
            angle += 360;
        }
        return angle;
    }



    /**
     * 返回向量
     *
     * @param startPoint
     * @param endPoint
     * @return
     */
    private static Point getVector(Point startPoint, Point endPoint) {
        return new Point(endPoint.getX() - startPoint.getX(),endPoint.getY() - startPoint.getY());
    }

//    private static Point getVector(double startX, double startY, double endX, double endY) {
//        return new Point(endPoint.getX() - startPoint.getX(),endPoint.getY() - startPoint.getY());
//    }

     static class Point {
        private double x;
        private double y;

         public Point(double x, double y) {
             this.x = x;
             this.y = y;
         }

         public double getX() {
             return x;
         }

         public void setX(double x) {
             this.x = x;
         }

         public double getY() {
             return y;
         }

         public void setY(double y) {
             this.y = y;
         }
     }

    public static String getMac(Context paramContext) {
        try {
            if (Build.VERSION.SDK_INT >= 23) {
                String str = getMacMoreThanM(paramContext);
                if (!TextUtils.isEmpty(str)) {
                    return str;
                }
            }

            WifiManager wifiManager = (WifiManager)paramContext.getSystemService(Service.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            if (wifiInfo != null) {
                return wifiInfo.getMacAddress();
            }
        } catch (Throwable var3) {
        }

        return null;
    }

    private static String getMacMoreThanM(Context paramContext) {
        try {
            Enumeration enumeration = NetworkInterface.getNetworkInterfaces();

            NetworkInterface networkInterface;
            String str;
            do {
                byte[] arrayOfByte;
                do {
                    do {
                        if (!enumeration.hasMoreElements()) {
                            return null;
                        }

                        networkInterface = (NetworkInterface)enumeration.nextElement();
                        arrayOfByte = networkInterface.getHardwareAddress();
                    } while(arrayOfByte == null);
                } while(arrayOfByte.length == 0);

                StringBuilder stringBuilder = new StringBuilder();
                byte[] var5 = arrayOfByte;
                int var6 = arrayOfByte.length;

                for(int var7 = 0; var7 < var6; ++var7) {
                    byte b = var5[var7];
                    stringBuilder.append(String.format("%02X:", b));
                }

                if (stringBuilder.length() > 0) {
                    stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                }

                str = stringBuilder.toString();
            } while(!networkInterface.getName().equals("wlan0"));

            return str;
        } catch (SocketException var9) {
            return null;
        }
    }


    public static void main(String[] args) {
//        int j = calAngle(460, 752,1128,521);
//        double j = calThreeAngle(100, 100, 200, 100, 200, 0);
//        double j = calThreeAngle(0, 0,10,10,10,20);
//        System.out.println("角度：" + j);
//        System.out.println("角度：" + calcRotationAngleInDegrees(10,20,20,10));
        Point startPoint = new Point(4,2);
        Point endPoint = new Point(4,8);
        Point basePoint = new Point(8,6);
        Point vectorStoE = getVector(startPoint, endPoint);
        Point vectorStoB = getVector(startPoint, basePoint);
        //根据两向量的外积判断点所在的位置。
        Double direction = vectorStoE.getX() * vectorStoB.getY() - vectorStoE.getY() * vectorStoB.getX();
        if (direction < 0) {
            System.out.println("在右侧");
        } else if (direction == 0) {
            System.out.println("在线上");
        } else {
            System.out.println("在左侧");
        }
    }

}
